package cn.cxy.demo

import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

fun getInfoByUrl(url: URL): String {
    var str = ""
    runCatching {
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.readTimeout = 5000
        connection.connectTimeout = 5000
        if (connection.responseCode == 200) {
            val inputStream = connection.inputStream
            str = streamToString(inputStream)
        }
    }
    return str
}

fun streamToString(inputStream: InputStream): String {
    val builder = StringBuilder()
    val reader = BufferedReader(InputStreamReader(inputStream))
    var con: String?
    runCatching {
        while (reader.readLine().also { con = it } != null) {
            builder.append(con)
        }
        reader.close()
    }
    return builder.toString()
}